/**
 * 
 */
package jvs.core.http;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * @author qiangli
 * 
 */
public class Adapter implements PI {
	private List<Handler> handlers = new ArrayList<Handler>();

	public Adapter() {
	}
	
	public List<Handler> getHandlers() {
		return handlers;
	}

	public void addHandler(Handler handler) {
		handlers.add(handler);
	}

	public void setHandlers(List<Handler> handlers) {
		this.handlers = handlers;
	}

	public void service(Context ctx, Socket s) {
		Thread th = new Servlet(ctx, s);
		th.start();
	}
	
	protected void log(String s) {
		System.out.println(s);
	}

	protected class Servlet extends Thread {
		private Context ctx = null;
		
		private Socket sock = null;

		private InputStream in = null;

		private OutputStream out = null;

		public Servlet(Context ctx, Socket sock) {
			this.ctx = ctx;
			this.sock = sock;
		}

		public void run() {
			try {
				in = sock.getInputStream();
				out = sock.getOutputStream();

				Request req = new Request();
				Response res = new Response();
				//
				req.parse(in);
				req.context = ctx;
				res.setOutputStream(out);
				
				service(req, res);
				//
				log("closing socket");

				in.close();
				out.close();
				sock.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		protected void service(Request req, Response res) throws Exception {
			for (Handler h : handlers) {
				log(h+": "+req);
				if (h.handle(req, res)) {
					return;
				}
			}
			log("no handler available to service this request");
		}
	}
}
